<?php
declare (strict_types = 1);

namespace app\user\model;

use app\common\model\BaseModel;
use think\Model;

/**
 * @mixin \think\Model
 */
class UserCash extends BaseModel
{
    public $page = '';//分页数据
    public $count = '';//数据总数
    public $error = '';//报错
    public $field = 'amount as balance,rate,status,remarks,add_time';


    /*
     * 获取用户余额提现记录
     */
    public function withdrawaList($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            //按时间筛选
            $data = Input('post.');
            $query = ['page'=> (isset($data['page'])?$data['page']:1)];
            $day = isset($data['time']) ? strtotime($data['time']) : strtotime(date('Y-m',time()));
            $end =  strtotime(date('Y-m',$day)." +1 month");
            $where[] = ['uid','=',$id];
            $where[] = ['is_delete','=',0];
            $where[] = ['type','=',2];
            if(!empty($data['type']))
                $where[] = ['status','=',$data['type']];
            $where[] = ['add_time','>=',$day];
            $where[] = ['add_time','<',$end];

            $statusMap = [
                '1'=>'申请中',
                '2'=>'待打款',
                '3'=>'已打款',
                '4'=>'打款失败',
                '5'=>'已驳回',
            ];
            $this->queryList($query,$this->field,$where,'add_time desc');
            $this->where = $where;
            if($this->list['data']){
                foreach($this->list['data'] as $k=>$v){
                    $this->list['data'][$k]['balance'] = getformat($v['balance']);
                    $this->list['data'][$k]['rate'] = getformat($v['rate']);
                    $this->list['data'][$k]['add_time'] = date('Y-m-d H:i',$v['add_time']);
                    $this->list['data'][$k]['status'] = $statusMap[$v['status']];
                    $this->list['data'][$k]['type'] = '余额提现';
                }
            }
            return $this->list;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    /*
     * 获取用户喵呗兑换记录
     */
    public function exchangeList($id,$isReturn = 0){
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            $query = ['page'=> (isset($data['page'])?$data['page']:1)];
            //按时间筛选
            $day = isset($data['time'])&&!empty($data['time']) ? strtotime($data['time'].'-01') : strtotime(date('Y-m-01',time()));
            $end =  strtotime(date('Y-m-01',$day)." +1 month");
            $where[] = ['uid','=',$id];
            $where[] = ['is_delete','=',0];
            $where[] = ['type','=',1];
            $where[] = ['status','=',3];
            if($isReturn==0){
                $where[] = ['add_time','>=',$day];
                $where[] = ['add_time','<',$end];
            }
            $this->queryList($query,'gold as balance,rate,status,remarks,add_time',$where,'add_time desc');
            $this->where = $where;
            if($this->list['data']){
                foreach($this->list['data'] as $k=>$v){
                    $this->list['data'][$k]['type'] = '喵呗兑换';
                    $this->list['data'][$k]['balance'] = getformat($v['balance']);
                    $this->list['data'][$k]['add_time'] = date('Y-m-d H:i', $v['add_time']);
                    unset($this->list['data'][$k]['status']);
                    unset($this->list['data'][$k]['remarks']);
                }
            }
            return $this->list;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    /*
     * 获取用户喵呗兑换记录
     */
    public function exchangeMiao($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            if(empty($data['miao'])||!is_numeric($data['miao'])) exception('请输入要兑换的喵呗!');
            $miao =  getformat($data['miao']*100);
            if(empty($data['miao'])||$data['miao'] < 0||$data['miao'] > $miao)
                exception('请填写正确的喵呗数量，只保留小数点后2位!');
            $miao = (int) ($data['miao']*100);
            $model = new UserWallet();
            $wallet = $model->where(['uid'=>$id,'is_delete'=>0])->find();
            if(empty($wallet)) exception('喵呗不足!');
            if($wallet['miao'] < $miao)  exception('您的喵呗不足!');
            $ins = [
                'uid' => $id,
                'type' => 1,
                'gold' => $miao,
                'status' => 3,
                'add_time' => time(),
            ];
            $this::startTrans();
            $mid = $this->insertGetId($ins);
            $model->where(['uid'=>$id])->dec('miao',$miao)->update();
            $model->where(['uid'=>$id])->inc('balance',$miao)->update();
            $uwid = (new WalletOperationLog())->insertGetId(['uid'=>$id,'reward'=>$miao,'status'=>2,'type'=>2,'extend'=>'user_cash','extend_id'=>$mid,'describe'=>'喵呗兑换','add_time'=>time()]);
            $this::commit();
            return true;
        }catch (\Exception $e){
            $this::rollback();
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }
}
